package demo.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * getFields ：获取所有的公有字段
 * getDeclareFields：获取所有字段，包括私有、受保护、默认、公有
 *
 *
 * @author weiyuewen 2020/6/9 16:34
 */
public class FieldCollector {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class reflectTargetClass = Class.forName("demo.reflect.ReflectTarget");
        System.out.println("=================获取所有公有的字段=================");
        Field[] fieldArray = reflectTargetClass.getFields();
        for (Field f:fieldArray){
            System.out.println(f);
        }
        System.out.println("=================获取所有字段=================");
        Field[] allFieldArray = reflectTargetClass.getFields();
        for (Field f:allFieldArray){
            System.out.println(f);
        }
        System.out.println("=================获取公有字段并调用=================");
        Field publicField = reflectTargetClass.getField("name");
        ReflectTarget reflectTarget = (ReflectTarget) reflectTargetClass.getConstructor().newInstance();
        publicField.set(reflectTarget, "待反射一号");
        System.out.println(reflectTarget.name);
        System.out.println("=================获取私有字段并调用=================");
        Field privateField = reflectTargetClass.getDeclaredField("targetInfo");
        privateField.setAccessible(true);
        privateField.set(reflectTarget, "12224455");
        System.out.println(reflectTarget);
    }


}
